<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-06-11 16:57:45
 */

namespace Ldy\Controller;

use Ldy\Model;
use support\Request;
use Ldy\Lib\FilesUpload;
use Tinywan\Storage\Exception\StorageException;

class BaseAdmin
{

    /**
     * 开启/关闭 系统操作日志记录 在类方法中 添加注释 ，格式为json如下
     * {"请求类型"："GET、POST等":{"title"=>"日志标题"}}
     *
     * @var array
     */
    protected $isRecordLogs = true;
    /**
     * 无需登录的方法及鉴权
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = [];

    /**
     * 标题
     *
     * @var string
     */
    protected $title = '';

    protected $formSuccessText = '创建成功！';

    /**
     * 列表页对外接口
     * {"GET":{"title":"访问{title}列表"}}
     *
     * @return void
     */
    public function index()
    {
        $grid = $this->grid()->get();
        return $this->successJson($grid);
    }


    /**
     * 创建表单，外部接口
     *
     * @return void
     */
    public function create()
    {
        $data = $this->form()->getForm();
        return $this->successJson($data);
    }

    /**
     * 数据保存
     * {"POST":{"title":"新建{title}"}}
     * @param Request $request
     * @return void
     */
    public function store(Request $request)
    {
        $postData = $request->post();

        $res = $this->form()->save($postData);

        if ($res instanceof Model)  return $this->successJson($res, $this->formSuccessText);

        return $this->errorJson($res);
    }

    public function show(Request $request, Int $id)
    {
        $show = $this->detail($id)->get();
        return $this->successJson($show);
    }

    /**
     * 修改数据
     * {"PUT":{"title":"修改{title}"}}
     * @param Request $request
     * @param Int $id
     * @return void
     */
    public function update(Request $request, Int $id)
    {

        $data = $request->post();

        $res = $this->form()->update($id, $data);

        if ($res instanceof Model) return $this->successJson($res, '修改成功！');

        return $this->errorJson($res);
    }

    /**
     * 删除数据
     * {"DELETE":{"title":"删除{title}"}}
     * @param Request $request
     * @param Int $id
     * @return void
     */
    public function destroy(Request $request, Int $id)
    {
        $this->grid()->model()->dataModel()->destroy($id);
        return $this->successJson($id, '删除成功！');
    }

    /**
     * 获取标题
     *
     * @return void
     */
    public function getTitle()
    {
        return $this->title;
    }

    public function upload(bool $returnVal = false, array $conf = [], string $storage = 'local_admin')
    {
        try {

            $config = [
                "include"=>[],//允许文件类型
                "single_limit"=> 1024*500,
                "total_limit" => 1024*500
            ];

            if(!empty($conf)) $config = array_merge($config, $conf);

            $res = FilesUpload::init($storage,$config)->uploadFile(); // 初始化。 默认为本地存储：local，阿里云：oss，腾讯云：cos，七牛：qiniu
            //$res = Storage::uploadFile($config);
            $res = isset($res[0]) ? $res[0] : $res;
            // $res['filePath'] = $res['url'];

            return $returnVal ? $res:$this->successJson($res);
            
        } catch (StorageException $e) {
            
            return $returnVal ?  $e->getMessage():$this->errorJson($e->getMessage());
        }
    }

    /**
     * 表单配置，内部接口
     *
     * @return object
     */
    protected function form()
    {
    }

    /**
     * 列表页，内部接口
     *
     * @return \Ldy\Lib\Grid
     */
    protected function grid()
    {
    }



    /**
     * 数据详情
     * @param Int $id
     * @return \Ldy\Lib\Show
     */
    protected function detail(Int $id)
    {
    }


    protected $code = [
        'success' => 200, //请求成功，返回数据
        'not-auth' => 401, //请求未授权，适合未登录返回
        'refuse' => 403 //拒绝请求，缺少参数或参数格式错误
    ];

    protected function successJson($data = [], $msg = '请求成功！')
    {
        $code = $this->code['success'];
        $res = ['code' => $code];
        if (is_string($data)) {
            $msg = $data;
        } else {
            $res['data'] = $data;
        }

        $res['msg'] = $msg;


        return json($res);
    }

    protected function errorJson($msg = '请求失败！', $code = 'refuse')
    {
        $res = ['code' => $this->code[$code], 'msg' => $msg];
        return json($res);
    }


    protected function password_encode($pass)
    {
        return password_hash(md5($pass), PASSWORD_DEFAULT);
    }

    protected function password_ver($input_pass, $db_pass)
    {
        return password_verify(md5($input_pass), $db_pass);
    }
}
